package com.taptech.doufu.ui.activity;

import android.animation.ObjectAnimator;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;

import com.taptech.doufu.R;
import com.taptech.doufu.bean.MineAbstractBean;
import com.taptech.doufu.ui.view.drawcircle.BaseRecyclerViewViewHolder;
import com.taptech.doufu.ui.view.drawcircle.MyRecyclerView;
import com.taptech.doufu.ui.view.drawcircle.MySwipeRefreshLayout;
import com.taptech.doufu.ui.view.drawcircle.RecyclerViewAdapterAsListView;
import com.taptech.doufu.ui.fragment.DoufuContentFragment;
import com.taptech.doufu.util.DiaobaoUtil;
import com.taptech.doufu.util.SharedPreferenceUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

/**
 * Created by longsiyang on 15/12/28.
 */
public class CartoonLatestFragment extends DoufuContentFragment
{

    private ImageView chooseTypeStaggle;
    int currentLayoutType = 2;
    StaggeredGridLayoutManager layoutManager;
    static private boolean isTopLayoutVisiable = true;
    private List<MineAbstractBean> mDataList;
    static final private int topLayoutHeight = 100;
    private int currentScanPos = 0;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        rootView = inflater.inflate(R.layout.drawcircle_cartoon_fragment_layout, container, false);
        mContext = getActivity();
        initData();

        initView();
        //拉取数据
        listViewRefresh();
        initWaitWindow();
        return rootView;
    }

    @Override
    protected void initData()
    {
        super.initData();
        this.mDataList = super.mDataList;
        currentLayoutType = SharedPreferenceUtil.getCartoonDisplayType(mContext, 2);
    }

    @Override
    protected void initView()
    {
        super.initView();
        waitBar = (ProgressBar) rootView.findViewById(R.id.xlistview_footer_progressbar);
        swipeLayout = (MySwipeRefreshLayout) rootView.findViewById(R.id.swipe_container);
        swipeLayout.setOnRefreshListener(new MySwipeRefreshLayout.OnRefreshListener()
        {
            @Override
            public void onRefresh()
            {
                listViewRefresh();
                //关闭刷新动画
                swipeLayout.setRefreshing(false);
                //关闭下拉使能已免
                swipeLayout.setEnabled(false);
                //显示顶部刷新等待窗
                waitBar.setVisibility(View.VISIBLE);
            }
        });
        adapter = new RecyclerViewAdapterAsListView(mContext, mDataList);
        listView = (MyRecyclerView) rootView.findViewById(R.id.recycler_view_id);
        listView.setAdapter(adapter);
        setLayoutManager(currentLayoutType);
        listView.setLayoutManager(layoutManager);
        chooseTypeStaggle = (ImageView) rootView.findViewById(R.id.draw_layout_type_change);
        chooseTypeStaggle.setOnClickListener(topLayoutClickListener);
        listView.setOnScrollToTopListener(new MyRecyclerView.OnScrollToTopListener()
        {
            @Override
            public void refresh()
            {
                swipeLayout.setEnabled(true);
            }

            @Override
            public void notAtTopInScrollView(int offestY, int directionY)
            {
                swipeLayout.setEnabled(false);
                if (Math.abs(directionY) > 3)
                {
                    if (offestY > topLayoutHeight && directionY > 0)
                    {
                        topLayoutHide(true);
                    } else
                    {
                        topLayoutHide(false);
                    }
                }
                currentScanPos = layoutManager.findFirstVisibleItemPositions(null)[0];

            }
        });
        listView.setOnScrollToBottomListener(new MyRecyclerView.OnScrollToBottomListener()
        {
            @Override
            public void loadMore()
            {
                listViewLoadMore();
            }
        });
    }

    /**
     * 顶部选择按钮监听
     */
    View.OnClickListener topLayoutClickListener = new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            switch (v.getId())
            {
                case R.id.draw_layout_type_change:
                    setTopLayoutUi();
                    break;
            }
        }
    };

    @Override
    protected void displayHttpData(JSONObject data)
    {
        try
        {
            if (adapter == null)
            {
                return;
            }
            // 判断是否还有更多内容
            if (data.has("last"))
            {
                if (last.equals(data.getString("last")))
                {
                    hasMoreContent = false;
                    adapter.pullComplete(true);

                } else
                {
                    hasMoreContent = true;
                    adapter.pullComplete(false);

                }
            } else
            {
                hasMoreContent = false;
                adapter.pullComplete(true);
            }


            // 如果是第一波数据
            if (last.equals("") && mDataList != null)
            {
                mDataList.clear();
                adapter.notifyDataSetChanged();
            }
            JSONArray jsonArray = data.getJSONArray(dataName);
            List dataList = DiaobaoUtil.json2list(classType, jsonArray);
            mDataList.addAll(dataList);
            if (currentLayoutType == 2)
            {
                setSpecialTypeToBean(BaseRecyclerViewViewHolder.TWO_SPAN_DISPLAY, 1);
            } else
            {
                setSpecialTypeToBean(BaseRecyclerViewViewHolder.TWO_SPAN_DISPLAY, 0);
            }
            adapter.notifyDataSetChanged();
            last = data.getString("last");
        } catch (JSONException e)
        {
            e.printStackTrace();
        }
    }

    /**
     * 设置展示的布局类型
     */
    private void setTopLayoutUi()
    {

        if (layoutManager != null && listView != null)
        {
            if (currentLayoutType == 1)
            {
                currentLayoutType = 2;
            } else if (currentLayoutType == 2)
            {
                currentLayoutType = 1;
            }
            if (currentLayoutType == 2)
            {
                chooseTypeStaggle.setImageResource(R.drawable.one_span_btn_icon);
                setSpecialTypeToBean(BaseRecyclerViewViewHolder.TWO_SPAN_DISPLAY, 1);
            } else
            {
                chooseTypeStaggle.setImageResource(R.drawable.two_span_btn_icon);
                setSpecialTypeToBean(BaseRecyclerViewViewHolder.TWO_SPAN_DISPLAY, 0);
            }
            SharedPreferenceUtil.saveCartoonDisplayType(getActivity(), currentLayoutType);
            setLayoutManager(currentLayoutType);
            listView.scrollToPosition(currentScanPos);
        }
    }

    private void topLayoutHide(boolean hide)
    {
        if (hide != isTopLayoutVisiable)
        {
            return;
        } else
        {
            ObjectAnimator objectAnimator = null;
            if (hide)
            {
                objectAnimator = ObjectAnimator.ofFloat(chooseTypeStaggle, "translationY", 0, chooseTypeStaggle.getMeasuredHeight() + 100);
            } else
            {
                objectAnimator = ObjectAnimator.ofFloat(chooseTypeStaggle, "translationY", chooseTypeStaggle.getMeasuredHeight() + 100, 0);
            }
            if (objectAnimator != null)
            {
                objectAnimator.setDuration(500);
                objectAnimator.start();

                isTopLayoutVisiable = !hide;
            }
        }
    }

    private void setLayoutManager(int span)
    {
        layoutManager = new StaggeredGridLayoutManager(span, StaggeredGridLayoutManager.VERTICAL);
        listView.setLayoutManager(layoutManager);


    }

    /**
     * 为所有的数据加上specialType
     *
     * @param specialType
     * @param sign        1为或上 0为与除
     */
    private void setSpecialTypeToBean(int specialType, int sign)
    {
        if (mDataList != null)
        {
            if (sign == 1)
            {
                for (MineAbstractBean bean : mDataList)
                {
                    bean.setSpecialType((bean.getSpecialType() | specialType));
                }
            } else if (sign == 0)
            {
                for (MineAbstractBean bean : mDataList)
                {
                    bean.setSpecialType((bean.getSpecialType() & (~specialType)));
                }
            }

        }
    }
}
